import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import admin from './children/admin'
import presentation from './children/presentation'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login.vue'),
    meta: {
      title: '登录'
    }
  },
  {
    path: '/create',
    name: 'create',
    component: () => import('../views/admin/create/index.vue'),
    meta: {
      title: '创建文章'
    }
  },
  {
    ...admin
  },
  {
    ...presentation
  }
]

// 获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
// 修改原型对象中的push方法，replace方法就把VueRouter.prototype.push的push换成replace即可
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  mode: 'history',
  routes,
  // 置顶
  scrollBehavior(to, from, saveTop) {
    if (saveTop) {
      return saveTop
    } else {
      return { x: 0, y: 0 }
    }
  }
})

router.beforeEach((to, from, next) => {
  const { name } = store.state.site.siteInfo
  const title = to.meta.title ? to.meta.title + '-' : ''
  if (name) {
    document.title = title + name
  } else {
    store.dispatch('getSiteInfo').then(res => {
      document.title = title + res.name
      document.querySelector('link[rel*="icon"]').href = store.state.site.siteInfo.iconUrl
    })
  }
  next()
})

export default router
